<template>
  <div class="page">
    <div class="head">
      <div class="head-box">
        <div class="box-item">订单名称：{{ orderItem.orderName }}</div>
        <div class="box-item">客户姓名：{{ orderItem.custName }}</div>
        <div class="box-item">
          订单总金额（元）：￥{{ orderItem.orderActualAmt }}
        </div>
      </div>
      <div class="head-box">
        <div class="box-item">商品数量：{{ orderItem.goodsTotalQty }}</div>
        <div class="box-item">
          订单状态：
          <Tag :color="this.$dict.orderStatus.color(orderItem.orderStatus)">{{this.$dict.orderStatus.name(orderItem.orderStatus)}}</Tag>
        </div>
        <div class="box-item">
          订单时间：{{ timestampToTime(orderItem.postTime) }}
        </div>
      </div>
      <div class="head-box">
        <div class="box-item">收货人：{{ orderItem.consigneeName }}</div>
        <div class="box-item">
          收货人电话：{{ orderItem.consigneeMobile }}
        </div>
        <div class="box-item">
          收货地址：{{ orderItem.provinceName }}/{{ orderItem.cityName }}/{{orderItem.countyName}}/{{ orderItem.addressDetail }}
        </div>
      </div>
    </div>
    <div class="main">
      <Table border :columns="columns" :data="dataGrid"></Table><br>
      <div v-show="expressForm">
        <Divider>填写寄件信息</Divider>
        <Form :label-width="140" style="width: 50%">
          <FormItem label="物品名称" required>
            <Input v-model="formData.cargoName" placeholder="请输入物品名称"></Input>
          </FormItem>
          <FormItem label="发货人" required>
            <Input v-model="formData.senderName" placeholder="请输入发货人"></Input>
          </FormItem>
          <FormItem label="发货人手机号" required>
            <Input v-model="formData.senderMobile" placeholder="请输入发货人手机号"></Input>
          </FormItem>
          <FormItem label="发货地区选择" required>
            <Cascader :data="regionArray" @on-change="regionSelector" :load-data="loadRegion"></Cascader>
          </FormItem>
          <FormItem label="发货地详情">
            <Input v-model="formData.senderAddress" placeholder="请输入发货地详细地址"></Input>
          </FormItem>
          <FormItem label="物品总重量(KG)">
            <InputNumber style="width:180px" v-model="preOrder.cargoWeight" placeholder="请输入物品总重量"></InputNumber>
          </FormItem>
        </Form>
        <div style="text-align:center">
          <Button type="primary" @click="QueryFee">平台物流发货</Button>
          <Button @click="OfflineSend">线下自助发货</Button>
        </div>
      </div>
      
      <div v-if="onlineSend === 0">
        <Divider>选择平台物流服务商</Divider>
        <div style="margin: 15px 0;background-color:#eee;padding:18px 10px">
          <Card v-for="(item,index) in logisticsCorps" :key="index" class="express-card">
            <div @click="checktExpress(item)" style="width:100%;height:100%;position:absolute;z-index:100"></div>
            <h2>{{item.corpName}}</h2>
            <section v-if="item.status" style="font-size:12px;color:gray">￥<big style="font-size:21px;color:#fb7777">{{item.freightAmt}}</big></section>
            <cite v-if="item.status" style="font-size:12px;color:gray">{{item.corpType}},预计运费 </cite>
            <cite v-else style="font-size:12px;color:orange">{{item.errorMsg}} </cite>
            <Icon v-if="checkExpressCode === item.corpCode" style="position:absolute;top:10px;right:10px" size="24" color="#27cb65" type="md-checkmark-circle" />
            <Icon v-else style="position:absolute;top:10px;right:10px" size="24" color="#dedede" type="md-checkmark-circle" />
          </Card>
        </div>
      </div>

      <div v-if="onlineSend === 1">
        <Divider>线下自助发货</Divider>
        <div style="margin: 15px 0;padding:18px 10px">
          <Form :label-width="140" style="width: 50%">
            <FormItem label="发货类型" required>
              <Select placeholder="选择发货类型" clearable v-model="formData.logisticsType">
                <Option :value="1">快递公司</Option>
                <Option :value="2">同城配送</Option>
                <Option :value="3">虚拟发货</Option>
                <Option :value="4">自提/到店</Option>
              </Select>
            </FormItem>
            <FormItem v-if="formData.logisticsType === 1 || formData.logisticsType === 2" label="快递公司" required>
              <Select placeholder="选择快递公司" clearable v-model="formData.corpCode">
                <Option v-for="item in seletions" :key="item.id" :value="item.code">{{item.name}}</Option>
              </Select>
            </FormItem>
            <FormItem v-if="formData.logisticsType === 1 || formData.logisticsType === 2" label="物流运单号">
              <Input v-model="formData.waybillNo" placeholder="请输入物流运单号"></Input>
            </FormItem>
          </Form>
        </div>
      </div>
      <div style="text-align:center" v-if="onlineSend && (orderItem.orderStatus==0||orderItem.orderStatus==1)">
        <Button @click="expressForm = true;onlineSend = null" type="dashed">上一步</Button>
        <Button @click="Submit" type="success">一键发货</Button>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "Delivery",
  data() {
    return {
      expressForm: true,
      onlineSend: null,
      checkExpressCode: null,
      checkExpressName: null,
      seletions: this.$dict.logisticsCorp.data,
      dataGrid:[],
      regionArray: [],
      logisticsCorps: [],
      selectRegions: [],
      preOrder: {
        corpCode: null,
        cargoWeight: null,
        senderProvince: null,
        senderCity: null,
      },
      formData: {
        logisticsType: 1, //1快递公司，2同城配送，3虚拟商品，4用户自提
        printType: 1, //00仅下单不打印，1生成图片短链
        shopOrderId: null,
        corpCode: null,
        senderName: null,
        senderMobile: null,
        senderAddress: null,
        recvName: null,
        recvMobile: null,
        recvAddress: null,
        cargoName: null,
        waybillNo: null,
        corpName: null,
        shopId: this.$store.getShop('shopId'),
        orgId: this.$store.getOrg('orgId')
      },
      columns: [
        {
          title: "商品图片",
          key: "goodsImg",
          width: 100,
          render: (h, params) => {
            return h("div", [
              h("img",{
                  attrs: {src: params.row.goodsImg,},
                  style: {width: "50px",height: "46px",},
                },
                "View"
              ),
            ])
          },
        },
        {
          title: "SKUID",
          key: "skuId",
          width: 220
        },
        {
          title: "商品名称",
          key: "goodsName",
        },
        {
          title: "规格/型号",
          key: "goodsSpec",
        },
        {
          title: "订单数量",
          key: "goodsQty",
          width: 150,
        },
        {
          title: "单价(元)",
          key: "salePrice",
          width: 150,
          sortable: true,
          render: (h, params) => {
            return h("div", [
              h("a", { style: { fontSize: "12px", color: "gray" } }, "￥"),

              h("span", params.row.salePrice),
            ]);
          },
        },
        {
          title: "总金额(元)",
          key: "actualAmt",
          width: 150,
          render: (h, params) => {
            return h("div", [
              h("a", { style: { fontSize: "12px", color: "gray" } }, "￥"),

              h(
                "span",
                this.goodsAllMoney(params.row.salePrice, params.row.goodsQty)
              ),
            ]);
          },
        }
      ]
    };
  },
  watch: {
    tableData(newVal) {
      /* newVal.forEach(item=>{
        if(!item.currentInventory){
          item.currentInventory = 0
        }
        this.$set(item, "shelfLable", [])
      }) */
      this.dataGrid = newVal
      this.formData.cargoName = newVal[0].goodsName
    }
  },
  props: {
    tableData: Array,
    orderItem: Object,
    callbank: Function
  },
  created() {},
  methods: {
    init() {
      this.checkExpressCode = null
      this.checkExpressName = null
      this.onlineSend = null
      this.logisticsCorps.length = 0
      this.regionInit()
    },
    getExpressCorps() {
      new this.$rest({
        gateway: 'agroerp',
        service: "agroerp-tms",
        url: "/v1.0/logistics/corp/page",
        query: {
          equal: {
            lspType: 0,
          },
          pageIndex: 1,
          pageSize: 21
        },
        action: (res) => {
          if (res.data.code === 20000) {
            res.data.data.list.forEach(element => {
              this.queryExpressFee(element)
            });
          } else {
            this.$Message.error(res.data.msg)
          }
        },
      }).get();
    },
    queryExpressFee(logisticsCorp) {
      this.preOrder.corpCode = logisticsCorp.corpCode
      this.preOrder.recvProvince = this.orderItem.provinceName
      this.preOrder.recvCity = this.orderItem.cityName

      new this.$rest({
        gateway: 'agroerp',
        service: "agroerp-tms",
        url: "/v1.0/kd100/express/shop/query/freight",
        data: {
          pojo: this.preOrder
        },
        action: (res) => {
          if (res.data.code === 20000) {
            logisticsCorp.status = res.data.data.status
            if(res.data.data.status) {
              logisticsCorp.freightAmt = res.data.data.data.price
            } else {
              logisticsCorp.errorMsg = res.data.data.message
            }
            this.logisticsCorps.push(logisticsCorp)
          } else {
            this.$Message.error(res.data.msg)
          }
        },
      }).post();
    },
    checktExpress(item) {
      this.checkExpressCode = item.corpCode
      this.checkExpressName = item.corpName
    },
    regionInit() {
      new this.$rest({
				gateway: 'agrobiz',
        service: "agrobiz-uc",
        url: "/v1.0/plus/union/region/lazy",
				query: {
					equal: {
            regionId: "0"
          }
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						this.regionArray = data
					} else {
						this.$Message.error({
              content: res.data.msg
            })
					}
				}
			}).get()
    },
		loadRegion(item, callback) {
			item.loading = true
			new this.$rest({
				gateway: 'agrobiz',
        service: "agrobiz-uc",
        url: "/v1.0/plus/union/region/lazy",
				query: {
					equal: {
            regionId: item.id,
            regionLevel: 3
          }
				},
				action: (res)=>{
					if(res.data.code === 20000){
						const data = res.data.data
						item.children = data
						item.loading = false
            callback()
					} else {
						this.$Message.error({
              content: res.data.msg
            })
					}
				}
			}).get()
		},
    regionSelector(value, data) {
      console.log(data,'data')
      console.log(value,'value')
      this.selectRegions = data
      this.preOrder.senderProvince = data[0].label
      this.preOrder.senderCity = data[1].label
		},
    QueryFee() {
      if(!this.formData.senderName || !this.formData.senderMobile) {
        this.$Message.error('请输入发货人信息')
        return false
      }
      if(!this.preOrder.senderProvince || !this.preOrder.senderCity) {
        this.$Message.error('请选择发货地区')
        return false
      }
      if(!this.preOrder.cargoWeight) {
        this.$Message.error('请输入物品总重量')
        return false
      }
      this.logisticsCorps.length = 0
      this.expressForm = false
      this.onlineSend = 0
      this.getExpressCorps()
    },
    OfflineSend() {
      if(!this.formData.senderName || !this.formData.senderMobile) {
        this.$Message.error('请输入发货人信息')
        return false
      }
      if(!this.preOrder.senderProvince || !this.preOrder.senderCity) {
        this.$Message.error('请选择发货地区')
        return false
      }
      this.expressForm = false
      this.onlineSend = 1
    },
    Submit() {
      if(this.onlineSend === 0) {
        this.plfmSend()
      } else if(this.onlineSend === 1) {
        this.SelfSend()
      }
    },
    //平台物流发货
    plfmSend() {
      if(!this.checkExpressCode) {
        this.$Message.error('请完善发货信息')
        return false
      }
      this.formData.corpCode = this.checkExpressCode
      this.formData.corpName = this.checkExpressName
      this.formData.shopOrderId = this.orderItem.shopOrderId
      this.formData.recvName = this.orderItem.consigneeName
      this.formData.recvMobile = this.orderItem.consigneeMobile
      this.formData.recvAddress = this.orderItem.provinceName + this.orderItem.cityName + this.orderItem.countyName + this.orderItem.addressDetail
      this.formData.senderAddress = this.selectRegions[0].label + this.selectRegions[1].label + this.selectRegions[2].label + this.formData.senderAddress
      new this.$rest({
        gateway: 'agroerp',
        service: "agroerp-tms",
        url: "/v1.0/kd100/express/shop/send",
        data: {
          pojo: this.formData
        },
        action: (res) => {
          if (res.data.code === 20000) {
            this.$Message.success('发单成功')
            this.callbank()
          } else {
            this.$Message.error(res.data.msg)
          }
        },
      }).post()
    },
    //自助发货
    SelfSend() {
      if(this.formData.logisticsType <= 2 && !this.formData.corpCode) {
        this.$Message.error('请选择快递公司')
        return false
      }
      if(this.formData.logisticsType <= 2 && !this.formData.waybillNo) {
        this.$Message.error('请输入运单号')
        return false
      }
      if(this.formData.logisticsType <= 2) {
        this.formData.corpName = this.$dict.logisticsCorp.name(this.formData.corpCode)
      } else {
        this.formData.corpName = '自提/虚拟发货'
      }
      this.formData.shopOrderId = this.orderItem.shopOrderId
      this.formData.recvName = this.orderItem.consigneeName
      this.formData.recvMobile = this.orderItem.consigneeMobile
      this.formData.recvAddress = this.orderItem.provinceName + this.orderItem.cityName + this.orderItem.countyName + this.orderItem.addressDetail
      this.formData.senderAddress = this.selectRegions[0].label + this.selectRegions[1].label + this.selectRegions[2].label + this.formData.senderAddress
      new this.$rest({
        gateway: 'agroerp',
        service: "agroerp-tms",
        url: "/v1.0/plus/express/shop/send/self",
        data: {
          pojo: this.formData
        },
        action: (res) => {
          if (res.data.code === 20000) {
            this.$Message.success('发货成功')
            this.callbank()
          } else {
            this.$Notice.warning({
							title: "操作失败",
							desc: res.data.msg
						})
          }
        },
      }).post()
    },
    timestampToTime(timestamp) {
      return this.$date(timestamp,'yyyy-MM-dd HH:mm:ss');
    },
    goodsAllMoney(salePrice, goodsQty) {
      let moneyAll = (salePrice * goodsQty).toFixed(2);
      return moneyAll;
    },
  },
};
</script>
<style lang="less" scoped>
.page {
  width: 100%;
}
.head {
  width: 100%;
}
.head-box {
  display: flex;
  width: 100%;
  justify-content: space-between;
  min-height: 30px;
}
.head-box .box-item:nth-child(1) {
  width: 30%;
}
.head-box .box-item:nth-child(2) {
  width: 30%;
}
.head-box .box-item:nth-child(3) {
  width: 40%;
}
.btns{
  margin: 16px 0px;
}
.item-image{
  display: flex;
  align-items: flex-start;
}
.express-card {
  display:inline-block;width:24%;text-align:center;position:relative;margin:5px;vertical-align: top;padding: 10px;min-height: 120px;
}
</style>